<script setup>
import { computed, defineProps } from "vue";
import FieldLabel from "@/components/card/fields/FieldLabel.vue";
import FieldDisplay from "@/components/card/fields/FieldDisplay.vue";
import Blank from "@/components/card/fields/FieldBlank.vue";
import u from "./FieldUtil.js"
import FieldBlank from "@/components/card/fields/FieldBlank.vue";

const props = defineProps(["meta", "vm"]);
const { meta, vm } = props;
const cols = meta.cols || 4;
const MAX_COLS = 24;
const name = meta.model || "~";
const model = vm.getModelRef(name);
const NO_LABEL = 0;
const NO_LABEL_BUT_PLACE = 2;

function isVisible(x) {
  return (x.visible == null || x.visible == true)
    && vm.getState(x);
}

const fields = computed(() => {
  if (!(meta && meta.items)) {
    return [];
  }
  let items = meta.items.filter(x => isVisible(x));
  let size = items.length;
  let labelWidth = 2;
  let fieldWidth = Math.ceil(MAX_COLS / cols);


  let groups = [];
  for (var i = 0; i < size; i++) {
    let fieldMeta = items[i];
    let labelVisible = fieldMeta.labelVisible;
    let w = Number(fieldMeta.width) || "1";
    w = w > cols ? cols : w;
    let textWidth = (w * fieldWidth) - labelWidth;

    let fieldGroup = {
      "span": 0,
      "items": []
    }

    if (labelVisible == NO_LABEL) {
      textWidth = fieldWidth;
    } else {
      fieldGroup.items.push({
        "span": labelWidth,
        "component": labelVisible == NO_LABEL_BUT_PLACE ? FieldBlank : FieldLabel,
        "props": {
          "key": fieldMeta.name + "_Label",
          "title": fieldMeta.title
        }
      });
    }

    fieldGroup.items.push({
      "span": textWidth,
      "component": u.fields(fieldMeta),
      "props": {
        "key": fieldMeta.name + "_Display",
        "vm": vm,
        "meta": fieldMeta
      }
    });

    groups.push(fieldGroup);

    fieldGroup.span = sum(fieldGroup.items);
  }
  let rows = [];
  for (var i = 0; i < size;) {
    let row = {
      span: 0,
      items: []
    }
    for (; i < size;) {
      let group = groups[i];
      if ((row.span + group.span) <= MAX_COLS) {
        row.items.push(group);
        row.span = row.span + group.span;
        i++;
      } else {
        break;
      }
    }
    if (row.span < MAX_COLS) {
      let lastGroup = row.items[row.items.length - 1];
      lastGroup.items.push({
        "span": (MAX_COLS - row.span),
        "component": Blank,
        "props": {
          "key": "_Blank"
        }
      })
    }
    rows.push(row);
  }
  let returns = [];

  rows.forEach(r => {
    r.items.forEach(g => {
      g.items.forEach(c => {
        returns.push(c);
      });
    });
  })
  return returns;
});

function sum(arrs) {
  let spans = 0;
  arrs.forEach(x => {
    spans += x.span;
  });
  return spans;
}
</script>

<template>
  <el-row :gutter="25" :key="model.key">
    <el-col v-for="item in fields" :span="item.span">
      <component :is="item.component" v-bind="item.props" />
    </el-col>
  </el-row>
</template>
